package com.yikome.shop.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yikome.common.CommonService;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.yikome.shop.entity.Present;
import com.yikome.shop.repository.PresentRepository;
import com.yikome.utils.BeanUtils;

@Service
public class PresentService extends CommonService<Present, Long>{

	@Autowired
	private PresentRepository presentRepository;
	
	@Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    
    @Autowired
	public void setResourceDao(PresentRepository repository) {
		super.setCommonDao(repository);
	}

	public List<Present> findAllPresent() {
		return presentRepository.findAllPresent();
	}

	public Present findPresent(Long presentId) {
		return presentRepository.findPresent(presentId);
	}
	
	public Present presistPresent(Present present) {
		
		if(present.getId() != null) {
			Present source = findPresent(present.getId());
			Preconditions.checkArgument(source != null, "原始数据不存在");
			BeanUtils.copyProperties(present, source);
			return presentRepository.save(source);
		}else {
			return presentRepository.save(present);
		}
	}

	@Transactional
	public void deletePresent(Long presentId) {
		Present present = find(presentId);
		present.setYn(0);
		presentRepository.delete(present);
	}

	public List<Map<String, Object>> findPresentCombobox() {

		String contentSQL = "SELECT '' AS 'id' , '不设定' AS 'text' , 'dists/super/images/present_holder_non.png' AS 'thumb' FROM DUAL \n" + 
							"UNION \n" + 
							"SELECT s_present.id , s_present.`name`, s_present.thumb FROM s_present \n" ; 
		
		return jdbcTemplate.queryForList(contentSQL, ImmutableMap.of());
	}
}
